"""Emby客户端封装"""

import logging
from typing import List, Optional, Dict, Any
from datetime import datetime

from embyapi.api_client import ApiClient
from embyapi.configuration import Configuration
from embyapi.api import (
    SystemServiceApi, ItemsServiceApi, PlaylistServiceApi, 
    LibraryServiceApi, UserServiceApi
)
from embyapi.models import BaseItemDto, QueryResultBaseItemDto

logger = logging.getLogger(__name__)


class EmbyClient:
    """Emby客户端封装类"""
    
    def __init__(self, config: Dict[str, Any]):
        """初始化Emby客户端"""
        self.config = config
        self._setup_client()
        self._user_id: Optional[str] = None
    
    def _setup_client(self):
        """设置API客户端"""
        scheme = 'https' if self.config.get('https', False) else 'http'
        base_url = f'{scheme}://{self.config["host"]}:{self.config["port"]}'
        
        config = Configuration()
        config.host = base_url
        config.api_key['X-Emby-Token'] = self.config.get('token', '')
        
        self.client = ApiClient(config)
        
        # 手动设置API密钥头（embyapi库需要手动设置）
        self.client.set_default_header('X-Emby-Token', self.config.get('token', ''))
        
        # 初始化API实例
        self.system_api = SystemServiceApi(self.client)
        self.items_api = ItemsServiceApi(self.client)
        self.playlist_api = PlaylistServiceApi(self.client)
        self.library_api = LibraryServiceApi(self.client)
        self.user_api = UserServiceApi(self.client)
    
    async def test_connection(self) -> bool:
        """测试服务器连接"""
        try:
            info = self.system_api.get_system_info()
            logger.info(f"连接成功 - Emby版本: {info.version}")
            return True
        except Exception as e:
            logger.error(f"连接失败: {e}")
            return False
    
    async def get_user_id(self) -> str:
        """获取用户ID"""
        if self._user_id:
            return self._user_id
        
        if self.config.get('user_id'):
            self._user_id = self.config['user_id']
            return self._user_id
        
        try:
            users = self.user_api.get_users()
            if users:
                # 使用第一个用户或根据名称查找
                self._user_id = users[0].id
                logger.info(f"使用用户ID: {self._user_id}")
            else:
                raise ValueError("未找到可用用户")
        except Exception as e:
            logger.error(f"获取用户ID失败: {e}")
            raise
        
        return self._user_id
    
    async def get_libraries(self) -> List[Dict[str, Any]]:
        """获取媒体库列表"""
        try:
            # 使用aiohttp进行异步HTTP请求
            import aiohttp
            headers = {'X-Emby-Token': self.config.get('token', '')}
            url = f"{'https' if self.config.get('https', False) else 'http'}://{self.config['host']}:{self.config['port']}/Library/VirtualFolders"
            
            async with aiohttp.ClientSession() as session:
                async with session.get(url, headers=headers) as response:
                    if response.status == 200:
                        libraries_data = await response.json()
                        result = []
                        for lib in libraries_data:
                            result.append({
                                'id': lib.get('ItemId', ''),
                                'name': lib.get('Name', ''),
                                'type': lib.get('CollectionType', ''),
                                'locations': lib.get('Locations', [])
                            })
                        return result
                    else:
                        logger.error(f"获取媒体库失败: HTTP {response.status}")
                        return []
        except Exception as e:
            logger.error(f"获取媒体库失败: {e}")
            return []
    
    async def get_library_by_name(self, name: str) -> Optional[Dict[str, Any]]:
        """根据名称获取媒体库"""
        libraries = await self.get_libraries()
        for lib in libraries:
            if lib['name'] == name:
                return lib
        return None
    
    async def get_playlist_by_name(self, name: str) -> Optional[BaseItemDto]:
        """根据名称获取播放列表"""
        try:
            user_id = await self.get_user_id()
            playlists = self.items_api.get_items(
                user_id=user_id,
                include_item_types='Playlist',
                recursive=True
            )
            
            for playlist in playlists.items:
                if playlist.name == name:
                    return playlist
            return None
        except Exception as e:
            logger.error(f"查找播放列表失败: {e}")
            return None
    
    async def create_playlist(self, name: str) -> Optional[BaseItemDto]:
        """创建播放列表"""
        try:
            # 使用正确的API调用格式
            result = self.playlist_api.post_playlists(
                name=name,
                ids=''  # 初始为空
            )
            logger.info(f"创建播放列表: {name}")
            return result
        except Exception as e:
            logger.error(f"创建播放列表失败: {e}")
            return None
    
    async def get_or_create_playlist(self, name: str) -> Optional[BaseItemDto]:
        """获取或创建播放列表"""
        playlist = await self.get_playlist_by_name(name)
        if playlist:
            return playlist
        return await self.create_playlist(name)
    
    async def check_playlist_exists(self, name: str) -> bool:
        """检查播放列表是否存在"""
        playlist = await self.get_playlist_by_name(name)
        return playlist is not None
    
    async def delete_playlist(self, playlist_id: str) -> bool:
        """删除播放列表"""
        try:
            self.items_api.delete_items(ids=playlist_id)
            logger.info(f"删除播放列表: {playlist_id}")
            return True
        except Exception as e:
            logger.error(f"删除播放列表失败: {e}")
            return False
    
    async def get_playlist_items(self, playlist_id: str, limit: int = 1) -> List[BaseItemDto]:
        """获取播放列表项目（按时间倒序）"""
        try:
            user_id = await self.get_user_id()
            items = self.items_api.get_items(
                user_id=user_id,
                parent_id=playlist_id,
                sort_by='DateCreated',
                sort_order='Descending',
                limit=limit
            )
            return items.items
        except Exception as e:
            logger.error(f"获取播放列表项目失败: {e}")
            return []
    
    async def add_items_to_playlist(self, playlist_id: str, item_ids: List[str]) -> bool:
        """添加项目到播放列表"""
        try:
            self.playlist_api.post_playlists_by_id_items(
                id=playlist_id,
                ids=','.join(item_ids)
            )
            logger.info(f"添加 {len(item_ids)} 个项目到播放列表")
            return True
        except Exception as e:
            logger.error(f"添加项目到播放列表失败: {e}")
            return False
    
    async def search_items(
        self, 
        library_id: str, 
        start_index: int = 0,
        limit: int = 100,
        sort_by: str = 'DateCreated',
        sort_order: str = 'Ascending'
    ) -> QueryResultBaseItemDto:
        """搜索媒体库项目"""
        try:
            user_id = await self.get_user_id()
            return self.items_api.get_items(
                user_id=user_id,
                parent_id=library_id,
                recursive=True,
                include_item_types='Movie,Episode,Video',
                fields='MediaStreams,Width,Height,DateCreated',
                sort_by=sort_by,
                sort_order=sort_order,
                start_index=start_index,
                limit=limit
            )
        except Exception as e:
            logger.error(f"搜索项目失败: {e}")
            raise
    
    async def get_library_sample_items(self, library_id: str, limit: int = 5) -> QueryResultBaseItemDto:
        """获取媒体库的示例项目（用于封面显示）"""
        try:
            user_id = await self.get_user_id()
            return self.items_api.get_items(
                user_id=user_id,
                parent_id=library_id,
                recursive=True,
                include_item_types='Movie,Series,Episode,Video',
                fields='BackdropImageTags,ImageTags,PrimaryImageTag',
                sort_by='Random',
                limit=limit
            )
        except Exception as e:
            logger.error(f"获取媒体库示例项目失败: {e}")
            return None
    
    def close(self):
        """关闭客户端连接"""
        if hasattr(self, 'client'):
            self.client.close()